﻿<?php
class SLS_BoEditBo extends SLS_BoControllerProtected 
{
	
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(),false));
		$param = $this->_http->getParam("name");
		$model = SLS_String::substrAfterFirstDelimiter($param,"_");
		$db = SLS_String::substrBeforeFirstDelimiter($param,"_");
		$controllersXML = $this->_generic->getControllersXML();
		$controller = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/@name"));
		$ckColumns = array();
	
		$actions = $this->getActionsBo($model,$db);				
		$allActions = array("List".ucfirst($db)."_".SLS_String::tableToClass($model),"Add".ucfirst($db)."_".SLS_String::tableToClass($model),"Modify".ucfirst($db)."_".SLS_String::tableToClass($model),"Delete".ucfirst($db)."_".SLS_String::tableToClass($model),"Clone".ucfirst($db)."_".SLS_String::tableToClass($model),"Email".ucfirst($db)."_".SLS_String::tableToClass($model));
		
		if (SLS_Sql::getInstance()->getCurrentDb() != $db)
			SLS_Sql::getInstance()->changeDb($db);
		$columns = SLS_Sql::getInstance()->showColumns($model);
		foreach($columns as $column)
			if (strtolower($column->Type) == "longtext")
				array_push($ckColumns,$column->Field);
		
		// If reload
		if ($this->_http->getParam("reload_ck") == "true")
		{
			$bind_ck = $this->_http->getParam("bind_ckeditor");
			$ckColumnsSelected = $this->_http->getParam("ck_columns");
			$actionsCk = array("Add","Modify");
			$xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/backoffice.xml"));
			
			// Add ckeditor binding
			if (!empty($bind_ck))
			{
				foreach($actionsCk as $actionCk)
				{
					try{
						$xsl_head = file_get_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl");
						if (SLS_String::contains($xsl_head,'CKEDITOR.replace'))
						{
							$xsl_head_start = trim(SLS_String::substrBeforeFirstDelimiter($xsl_head,'<script type="text/javascript" src="{concat($sls_url_domain,\'/Public/Scripts/\',\'ckeditor/ckeditor.js\')}"></script>'."\n"))."\n";						
							$xsl_head_end = SLS_String::substrAfterFirstDelimiter($xsl_head,'</style>'."\n");							
							file_put_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl",$xsl_head_start.$xsl_head_end);
						}
						
						$xsl_head = file_get_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl");						
						$xsl_head_start = SLS_String::substrBeforeFirstDelimiter($xsl_head,'</xsl:template>');
						$xsl_body = '    <script type="text/javascript" src="{concat($sls_url_domain,\'/Public/Scripts/\',\'ckeditor/ckeditor.js\')}"></script>'."\n".
									'        <script type="text/javascript" src="{concat($sls_url_domain,\'/Public/Scripts/\',\'ckfinder/ckfinder.js\')}"></script>'."\n".
							        '        <script type="text/javascript">'."\n".
								    '            window.onload = function(){'."\n".
								    '                CKEDITOR.basePath = \'<xsl:value-of select="concat($sls_url_domain,\'/Public/Scripts/\',\'ckeditor/\')" />\';'."\n";
						
						$boBuildCk = 'var ckFields = [';
						if (is_array($ckColumnsSelected) && !empty($ckColumnsSelected))
						{
							foreach($ckColumnsSelected as $ckColumnSelected)
							{
								$result = array_shift($xmlBo->getTagsAttribute("//sls_configs/entry[@table='".strtolower($db)."_".strtolower($model)."' and @column='".$ckColumnSelected."' and @multilanguage = 'false']","multilanguage"));								
								foreach($this->_lang->getSiteLangs() as $lang)
								{
									if (!empty($result) && $lang != $this->_lang->getDefaultLang())
										continue;
									$xsl_body .= '                CKEDITOR.replace("'.$ckColumnSelected.'_'.$lang.'");'."\n";
									$boBuildCk .= '"'.$ckColumnSelected.'_'.$lang.'",';
								}
							}
						}
						if (SLS_String::endsWith(trim($boBuildCk),','))
							$boBuildCk = SLS_String::substrBeforeLastDelimiter($boBuildCk,',');
						$boBuildCk .= '];';
															
						$xsl_body .='                CKFinder.setupCKEditor(null,\'<xsl:value-of select="concat($sls_url_domain,\'/Public/Scripts/\',\'ckfinder/\')" />\');'."\n".
								    '            };'."\n".
									'            '.$boBuildCk.''."\n".
							        '        </script>'."\n".
							        '        <style type="text/css">'."\n".
							        '            .cke_skin_kama {'."\n".
							        '                display: block;'."\n".
							        '                float: left;'."\n".
							        '                margin-left:20px;'."\n".
							        '            }'."\n".
	        						'        </style>'."\n";
						$xsl_head_end = '    </xsl:template>'.SLS_String::substrAfterFirstDelimiter($xsl_head,'</xsl:template>');
						file_put_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl",$xsl_head_start.$xsl_body.$xsl_head_end);						
					}
					catch(Exception $e){}
				}
			}
			// Remove ckeditor binding
			else
			{
				foreach($actionsCk as $actionCk)
				{
					$xsl_head = file_get_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl");
					if (SLS_String::contains($xsl_head,'CKEDITOR.replace'))
					{
						$xsl_head_start = SLS_String::substrBeforeFirstDelimiter($xsl_head,'<script type="text/javascript" src="{concat($sls_url_domain,\'/Public/Scripts/\',\'ckeditor/ckeditor.js\')}"></script>'."\n")."\n";						
						$xsl_head_end = SLS_String::substrAfterFirstDelimiter($xsl_head,'</style>'."\n");
						file_put_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/".$actionCk.ucfirst($db)."_".SLS_String::tableToClass($model).".xsl",$xsl_head_start.$xsl_head_end);
					}
				}
			}
		}
		
		try{
			$xsl_add_head = file_get_contents($this->_generic->getPathConfig("viewsHeaders").$controller."/Add".ucfirst($db)."_".SLS_String::tableToClass($model).".xsl");
		}
		catch (Exception $e){
			$xsl_add_head = "";
		}
		
		$xml->startTag("bo");
		$xml->addFullTag("class",$param,true);
		$xml->addFullTag("db",$db,true);
		$xml->addFullTag("table",$model,true);
		$xml->addFullTag("ck_binding",(SLS_String::contains($xsl_add_head,'CKEDITOR.replace')) ? "true" : "false",true);
		$xml->startTag("ck_columns");
		foreach($ckColumns as $ckColumn)		
			$xml->addFullTag("ck_column",$ckColumn,true,array("selected"=>(SLS_String::contains($xsl_add_head,'CKEDITOR.replace("'.$ckColumn.'_'.$this->_lang->getDefaultLang().'")')) ? "true" : "false"));
		$xml->endTag("ck_columns");
		$xml->startTag("actions");
		foreach($actions as $action)
		{
			$xml->startTag("action");			
			$action = trim(SLS_String::substrBeforeFirstDelimiter($action,ucfirst($db)."_".SLS_String::tableToClass($model)));
			$xml->addFullTag("name",$action,true);
			if ($action == "List")
			{
				$source = file_get_contents($this->_generic->getPathConfig("actionsControllers").$controller."/List".ucfirst($db)."_".SLS_String::tableToClass($model).".controller.php");
				$source = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter(SLS_String::substrAfterFirstDelimiter($source,"public function action()"),"{"),'$boListing->constructList();');
				eval($source);
				$arrayFilters = array();
				$arrayColumns = array();
				$tmp = $boListing->__get("arrayFilters");
				for($i=0 ; $i<$count=count($tmp) ; $i++)
					array_push($arrayFilters,$tmp[$i]["column"]);
				$tmp = $boListing->__get("arrayColumns");
				for($i=0 ; $i<$count=count($tmp) ; $i++)
					array_push($arrayColumns,$tmp[$i]["column"]);
				$this->_generic->useModel($model,$db,"user");
				$class = ucfirst($db)."_".SLS_String::tableToClass($model);
				$object = new $class();
				$properties = $object->getParams();
				foreach($properties as $key => $value)
				{
					$comment = $object->getColumnComment($key,$model);
					$properties[$key] = (empty($comment)) ? $key : $comment;
				}
				$arrayJoin 	= $boListing->__get("join");
				if (is_array($arrayJoin) && !empty($arrayJoin))
				{
					foreach($arrayJoin as $firstJoin)
					{					
						$joinClassName = SLS_String::tableToClass($firstJoin);
						$this->_generic->useModel($joinClassName,$db,"user");
						$class = ucfirst($db)."_".SLS_String::tableToClass($joinClassName);
						$joinObj = new $class();
						$propertiesJoin = $joinObj->getParams();
						foreach($propertiesJoin as $key => $value)
						{
							$comment = $joinObj->getColumnComment($key,$joinObj->getTable());	
							if (!in_array($key,$properties))
								$properties[$key] = (empty($comment)) ? $key : $comment;
						}
					}
				}
				$xml->startTag("columns");
				foreach($properties as $key => $value)
				{
					$xml->startTag("column");
					$xml->addFullTag("name",$key,true);
					$xml->addFullTag("title",$value,true);
					$xml->addFullTag("selected_filters",(in_array($key,$arrayFilters)) ? "true" : "false",true);
					$xml->addFullTag("selected_columns",(in_array($key,$arrayColumns)) ? "true" : "false",true);
					$xml->endTag("column");
				}
				$xml->endTag("columns");
				$columnsC = SLS_Sql::getInstance()->getColumnsName($object->getTable());
				$cols = array();
				foreach($columnsC as $columnC)
				{
					$tmp = array("name" => $columnC, "desc" => $object->getColumnComment($columnC,$object->getTable()));
					array_push($cols,$tmp);
				}
				foreach($boListing->__get("join") as $join)
				{
					$columnsJoin = SLS_Sql::getInstance()->getColumnsName($join);
					foreach($columnsJoin as $colJoin)
						if (!in_array($colJoin,$columnsC))
						{
							array_push($columnsC,$colJoin);
							$tmp = array("name" => $colJoin, "desc" => $object->getColumnComment($colJoin,$join));
							array_push($cols,$tmp);
						}
				}
				$xml->startTag("groups");
				for($i=0 ; $i<$count=count($cols) ; $i++)
				{
					$xml->startTag("group");
					$xml->addFullTag("name",$cols[$i]["name"],true);
					$xml->addFullTag("desc",$cols[$i]["desc"],true);
					$xml->addFullTag("selected",(in_array($cols[$i]["name"],$boListing->__get("group"))) ? "true" : "false",true);
					$xml->endTag("group");
				}
				$xml->endTag("groups");
				$xml->startTag("default_order");
				$xml->addFullTag("column",$boListing->__get("column"),true);
				$xml->addFullTag("order",$boListing->__get("order"),true);
				$xml->endTag("default_order");
				$xml->startTag("default_limit");
				$xml->addFullTag("start",$boListing->__get("start"),true);
				$xml->addFullTag("length",$boListing->__get("length"),true);
				$xml->endTag("default_limit");
				$arrayAd 	= $boListing->__get("arrayAdd");
				$arrayMd 	= $boListing->__get("arrayModify");
				$arrayDl 	= $boListing->__get("arrayDelete");
				$arrayCl 	= $boListing->__get("arrayClone");
				$arrayEm 	= $boListing->__get("arrayEmail");
				
				$xml->startTag("default_actions");
				$xml->addFullTag("action_add",(empty($arrayAd)) ? "false" : "true",true);
				$xml->addFullTag("action_modify",(empty($arrayMd)) ? "false" : "true",true);
				$xml->addFullTag("action_delete",(empty($arrayDl)) ? "false" : "true",true);
				$xml->addFullTag("action_clone",(empty($arrayCl)) ? "false" : "true",true);
				$xml->addFullTag("action_email",(empty($arrayEm)) ? "false" : "true",true);
				$xml->endTag("default_actions");
				$xml->startTag("joins");
				$arrayJoin 	= $boListing->__get("join");
				if (is_array($arrayJoin) && !empty($arrayJoin))
				{
					foreach($arrayJoin as $join)
					{
						$xml->startTag("join");
						$xml->addFullTag("table",$join,true);
						$xml->endTag("join");
					}
				}
				$xml->endTag("joins");
			}
			else if ($action == "Add")
			{
				$source = file_get_contents($this->_generic->getPathConfig("actionsControllers").$controller."/Add".ucfirst($db)."_".SLS_String::tableToClass($model).".controller.php");
				$sourceE = explode("\n",$source);
				$redirect = true;
				foreach($sourceE as $line)
				{
					if (SLS_String::startsWith(trim($line),'$bo->setUrlToRedirect('))
					{
						$result = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($line,'$bo->setUrlToRedirect('),");");						
						if ($result == "\"\"")
							$redirect = false;
					}
				}
				$xml->addFullTag("redirect",($redirect) ? "true" : "false",true);
			}
			$xml->endTag("action");
		}
		$xml->endTag("actions");
		$xml->startTag("actions_absents");
		foreach($allActions as $action)
		{
			if (!in_array($action,$actions))
			{
				$xml->startTag("action_absent");
				$xml->addFullTag("name",trim(SLS_String::substrBeforeFirstDelimiter($action,ucfirst($db)."_".SLS_String::tableToClass($model))),true);
				$xml->endTag("action_absent");
			}
		}
		$xml->endTag("actions_absents");
		
		$models = $this->getAllModels();
		sort($models,SORT_REGULAR);
		
		$xml->startTag("models");		
		foreach($models as $curModel)
		{			
			$tableN = SLS_String::substrAfterFirstDelimiter($curModel,".");
			$dbN = SLS_String::substrBeforeFirstDelimiter($curModel,".");
			$classN = ucfirst($dbN)."_".SLS_String::tableToClass($tableN);
			
			if (SLS_String::startsWith($curModel,$db))
			{
				$this->_generic->useModel($tableN,$dbN,"user");			
				$userObj = new $classN();
				$xml->startTag("model");
				$xml->addFullTag("class",$classN,true);
				$xml->addFullTag("db",$dbN,true);
				$xml->addFullTag("table",$userObj->getTable(),true);
				$xml->endTag("model");
			}
		}
		$xml->endTag("models");
		$xml->startTag("urls");
		$xml->addFullTag("customize_bo",$this->_generic->getFullPath("SLS_Bo","CustomizeBo"),true);
		$xml->addFullTag("add_action_list",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"list"))),true);
		$xml->addFullTag("add_action_add",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"add"))),true);
		$xml->addFullTag("add_action_modify",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"modify"))),true);
		$xml->addFullTag("add_action_delete",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"delete"))),true);
		$xml->addFullTag("add_action_clone",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"clone"))),true);
		$xml->addFullTag("add_action_email",$this->_generic->getFullPath("SLS_Bo","AddBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"email"))),true);
		$xml->addFullTag("delete_action_list",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"list"))),true);
		$xml->addFullTag("delete_action_add",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"add"))),true);		
		$xml->addFullTag("delete_action_modify",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"modify"))),true);
		$xml->addFullTag("delete_action_delete",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"delete"))),true);
		$xml->addFullTag("delete_action_clone",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"clone"))),true);
		$xml->addFullTag("delete_action_email",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(0=>array("key"=>"name","value"=>$db."_".$model),1=>array("key"=>"type","value"=>"email"))),true);
		$xml->addFullTag("edit_action_add",$this->_generic->getFullPath("SLS_Bo","EditBoAdd",array(0=>array("key"=>"name","value"=>$db."_".$model))),true);
		$xml->endTag("urls");
		$xml->endTag("bo");
		
		$this->saveXML($xml);
	}
	
}
?>